#include "widget.h"
#include "ui_widget.h"
#include <QNetworkDatagram>

const QString& ser_ip = "127.0.0.1";
const quint16 port = 9090;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    socket = new QUdpSocket(this);

    connect(socket,&QUdpSocket::readyRead,this,&Widget::handle);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    //获取输入框里的内容
    QString send_str = ui->lineEdit->text();

    //构建发送的报文
    QNetworkDatagram gram(send_str.toUtf8(),QHostAddress(ser_ip),port);

    //发送出去
    socket->writeDatagram(gram);

    QString show_str = "sendto server: " + gram.senderAddress().toString() + " " + QString::number(gram.senderPort()) + " " + gram.data();
    ui->listWidget->addItem(show_str);

    //清理内容
    ui->lineEdit->setText("");
}

void Widget::handle()
{
    //读取消息
    QNetworkDatagram gram = socket->receiveDatagram();

    //显示观察
    QString show_str = "get: " + gram.senderAddress().toString() + " " + QString::number(gram.senderPort()) + " " + gram.data();
    ui->listWidget->addItem(show_str);
}
